package com.px.plan.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.px.common.annotation.Log;
import com.px.common.core.controller.BaseController;
import com.px.common.core.domain.AjaxResult;
import com.px.common.core.page.TableDataInfo;
import com.px.common.enums.BusinessType;
import com.px.common.utils.poi.ExcelUtil;
import com.px.framework.aes.AesSecurityParameter;
import com.px.plan.domain.PlanAction;
import com.px.plan.domain.PlanActionRecord;
import com.px.plan.domain.PlanActionUser;
import com.px.plan.domain.PlanVideoVo;
import com.px.plan.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 飞行行动Controller
 * 
 * @author WRJ
 * @date 2024-08
 */
@Api("飞行行动管理")
@RestController
@RequestMapping("/plan/action")
public class PlanActionController extends BaseController
{
    @Autowired
    private IPlanActionService planActionService;
    @Autowired
    private IPlanActionSchemeService planActionSchemeService;
    @Autowired
    private IPlanActionRecordService recordService;
    @Autowired
    private IPlanActionUserService planActionUserService;

    /**
     * 飞行行动列表
     */
    @ApiOperation("飞行行动列表")
    @PreAuthorize("@ss.hasPermi('plan:action:list')")
    @GetMapping("/list")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo list(PlanAction planAction)
    {
        startPage();
        List<PlanAction> list = planActionService.selectPlanActionList(planAction);
        return getDataTable(list);
    }

    /**
     * 我的飞行行动列表
     */
    @ApiOperation("我的飞行行动列表")
    @PreAuthorize("@ss.hasPermi('plan:action:myList')")
    @GetMapping("/myList")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo myList(PlanAction planAction)
    {
        planAction.setPilotId(getUserId() + "");
        startPage();
        List<PlanAction> list = planActionService.selectPlanActionList(planAction);
        return getDataTable(list);
    }

    /**
     * 导出飞行行动列表
     */
    @ApiOperation("导出飞行行动列表")
    @PreAuthorize("@ss.hasPermi('plan:action:list')")
    @Log(title = "飞行行动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @AesSecurityParameter
    public void export(HttpServletResponse response, PlanAction planAction)
    {
        List<PlanAction> list = planActionService.selectPlanActionList(planAction);
        ExcelUtil<PlanAction> util = new ExcelUtil<PlanAction>(PlanAction.class);
        util.exportExcel(response, list, "飞行行动数据");
    }

    /**
     * 飞行行动详情
     */
    @ApiOperation("飞行行动详情")
    @PreAuthorize("@ss.hasPermi('plan:action:list')")
    @GetMapping(value = "/{id}")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        PlanAction planAction = planActionService.selectPlanActionById(id);
        if (null != planAction) {
            PlanActionUser planActionUser = new PlanActionUser();
            planActionUser.setActionId(id);
            List<PlanActionUser> planActionUsers = planActionUserService.selectPlanActionUserList(planActionUser);
            planAction.setActionUsers(planActionUsers);
        }
        return success(planAction);
    }

    /**
     * 新增飞行行动
     */
    @ApiOperation("新增飞行行动")
    @PreAuthorize("@ss.hasPermi('plan:action:edit')")
    @Log(title = "新增飞行行动", businessType = BusinessType.INSERT)
    @PostMapping
    @AesSecurityParameter(outEncode = true)
    public AjaxResult add(@RequestBody PlanAction planAction)
    {
        Assert.notEmpty(planAction.getActionUsers(), "请选择行动人员");
        planAction.setCreateByName(getLoginUser().getUser().getNickName());
        planAction.setBeginTime(new Date());
        int result = planActionService.insertPlanAction(planAction);
        return toAjax(result);
    }

    /**
     * 修改行动
     */
    @ApiOperation("修改行动")
    @PreAuthorize("@ss.hasPermi('plan:action:edit')")
    @Log(title = "修改行动", businessType = BusinessType.UPDATE)
    @PutMapping
    @AesSecurityParameter(outEncode = true)
    public AjaxResult edit(@RequestBody PlanAction planAction)
    {
        return toAjax(planActionService.updatePlanAction(planAction));
    }

    /**
     * 结束行动
     */
    @ApiOperation("结束行动")
    @PreAuthorize("@ss.hasPermi('plan:action:end')")
    @Log(title = "结束行动", businessType = BusinessType.UPDATE)
    @PutMapping("/end")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult end(@RequestBody PlanAction planAction)
    {
        PlanAction entity = new PlanAction();
        entity.setId(planAction.getId());
        entity.setStatus(2);
        entity.setEndTime(new Date());
        int i = planActionService.updatePlanAction(entity);

        // 同步结束相关记录
        PlanActionRecord record = new PlanActionRecord();
        record.setActionId(planAction.getId());
        List<PlanActionRecord> planActionRecords = recordService.selectPlanActionRecordList(record);
        planActionRecords.forEach(r -> {
            r.setActionStatus(2);
            r.setFlightTimeEnd(DateUtil.beginOfSecond(new Date()));
            r.setFlightTime(DateUtil.between(r.getFlightTimeEnd(), r.getFlightTimeBegin(), DateUnit.SECOND));
            recordService.updatePlanActionRecord(r);
        });

        //发送mq消息到飞手mq
        planActionService.pushMqByEndPlan(entity.getId());

        //结束行动时，将录屏数据全部上传并存储
        planActionService.insertRecordVideo(planActionRecords);
        return toAjax(i);
    }

    /**
     * 删除飞行行动
     */
    @ApiOperation("删除飞行行动")
    @PreAuthorize("@ss.hasPermi('plan:action:remove')")
    @Log(title = "删除飞行行动", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult remove(@PathVariable Long[] ids) throws Exception {
        return toAjax(planActionService.deletePlanActionByIds(ids));
    }

    /**
     * 绑定飞行行动
     */
    @ApiOperation("绑定飞行行动")
    @PreAuthorize("@ss.hasPermi('plan:action:edit')")
    @Log(title = "绑定飞行行动", businessType = BusinessType.UPDATE)
    @PostMapping("/bind")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult bind(@ApiParam(value = "飞行行动ID", required = true) @RequestParam("id") Long id)
    {
        PlanAction planAction = planActionService.selectPlanActionById(id);
        Assert.notNull(planAction, "id不存在");

        if (null != planAction.getCommandId()) {
            if (!NumberUtil.equals(planAction.getCommandId(), getUserId())) {
                return AjaxResult.error(String.format("此任务被其他人(%s)绑定,操作失败", planAction.getCommandName()));
            }
        }
        return toAjax(planActionService.bindCommand(id, getUserId(), getUsername()));
    }

    /**
     * 解绑飞行行动
     */
    @ApiOperation("解绑飞行行动")
    @PreAuthorize("@ss.hasPermi('plan:action:edit')")
    @Log(title = "解绑飞行行动", businessType = BusinessType.UPDATE)
    @PostMapping("/unbind")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult unbind(@ApiParam(value = "飞行行动ID", required = true) @RequestParam("id") Long id)
    {
        PlanAction planAction = planActionService.selectPlanActionById(id);
        Assert.notNull(planAction, "id不存在");

        if (null == planAction.getCommandId()) {
            // 此任务无人指挥,不需要解绑
            return AjaxResult.success();
        } else {
            // 此任务有人指挥,但指挥人不是登录人
            if (!NumberUtil.equals(planAction.getCommandId(), getUserId())) {
                return AjaxResult.error(String.format("此任务被其他人(%s)绑定,操作失败", planAction.getCommandName()));
            }
        }
        return toAjax(planActionService.bindCommand(id, null, null));
    }

    @ApiOperation("视频录制")
    @PostMapping("/RecordVideo")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult RecordVideo(@RequestBody PlanVideoVo planVideoVo)
    {
        planActionService.recordVideo(planVideoVo);
        return success();
    }
}
